var express = require('express');
var router = express.Router();
var Register = require('../controllers/Register');
var Taobao = require('../controllers/taobao');
var sea = require("../common/sea")
var sqlOrm = require('../common/sqlModel');
const utils = require("../common/utils")
/* GET home page. */

let checkCutSign = ()=>{
    return  async (req, res, next) => {
        console.time("checkLogin")
        try {
            let body = req.body;
            if(req.method == "GET")
                body = req.query;

            var token =body.sign;

            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);

            if (JsonString.code != 200) {
                console.error("签名错误 返回-1",token)
                if(channelInfo[0].status != 1){
                    return next()
                }else {
                    return   res.end("-1");
                }
            }
            const decodedInfo = JSON.parse(JsonString.decoded);
            console.error("decodedInfo==================",decodedInfo)

            const id = decodedInfo.id;
            const time = decodedInfo.time;
            const Num = decodedInfo.Num;

            if(new Date().getTime() - time >= 10 * 1000){
                console.error("超时")
                return   res.end("-1");
            }

            let AccountInfo = await sqlOrm.app_account.findAsync({id});
            if(AccountInfo.length <= 0 ){
                console.error("用户不存在 返回-1",token)
                if(channelInfo[0].status != 1){
                    return next()
                }else {
                    return   res.end("-1");
                }
            }

            if (AccountInfo.cutNum <= 0){
                console.error("没有次数")
                return   res.end("-1");
            }

            next()

        }catch (e) {
            console.error("报错 返回-1",)
            console.timeEnd("checkLogin")
            return   res.end("-1");
        }

    }
};
let checkLogin = ()=>{
  return  async (req, res, next) => {
    console.time("checkLogin")
    try {
      let body = req.body;
      if(req.method == "GET")
        body = req.query;

      var channel =body.channel;
      var token   = body.token;
      if(!channel || !token){
        console.error("没有渠道 返回-1")
        return res.end("-1");
      }
      let channelInfo = await sqlOrm.channel.findAsync({channel});
      if (channelInfo.length <= 0){
        console.error("渠道不存在 返回-1",token)
        return    res.end("-1");
      }

      let JsonString = sea.decrypt(sea.key, sea.vi, token);
      if (typeof JsonString === 'string')
        JsonString = JSON.parse(JsonString);

      if (JsonString.code != 200) {
        console.error("签名错误 返回-1",token)
        if(channelInfo[0].status != 1){
          return next()
        }else {
          return   res.end("-1");
        }
      }
      const decodedInfo = JSON.parse(JsonString.decoded);
      console.error("decodedInfo==================",decodedInfo)

      const id = decodedInfo.id;
      let AccountInfo = await sqlOrm.app_account.findAsync({id});
      if(AccountInfo.length <= 0 ){
        console.error("用户不存在 返回-1",token)
        if(channelInfo[0].status != 1){
          return next()
        }else {
          return   res.end("-1");
        }
      }
      if(AccountInfo[0].status == -1 || JSON.parse(AccountInfo[0].aliveTime) * 1000 * 60 * 60 *24 + JSON.parse(AccountInfo[0].time)  < new Date().getTime()){
        console.error("非vip",channel)
        console.timeEnd("checkLogin")
        if(channelInfo[0].status != 1){
          return next()
        }else {
          return   res.end("-1");
        }
        return next()
      }
      next()

    }catch (e) {
      console.error("报错 返回-1",)
      console.timeEnd("checkLogin")
      return   res.end("-1");
    }

  }
};
let getBody = (req,res,cb)=>{
    console.log("getBody .method is",req.method)
    if (req.method == "GET"){
        body = req.query
    }else{
        if (!req.body.data) {
            console.error("{code:500,msg:参数不足}",req.body)
            var resultString = JSON.stringify({code:500,msg:"参数不足"});
            res.end(resultString)
            return
        }
        let signData = req.body.data;
        let chechInfo = utils.chechSing(signData)
        if (chechInfo.code != 200) {
            resultString = JSON.stringify(chechInfo)
            console.error(resultString)
            res.end(resultString)
            return
        }
        let signDecodedInfo = chechInfo.signDecodedInfo
        body = signDecodedInfo
    }
    console.log("URL is",req.url)
    console.log("客户端传入的数据是",body)
    return cb(body)
}
let retClient = (req,result)=>{
    console.log("返回客户端的数据是",result)
    if (req.method == "GET"){
        result = JSON.stringify(result)
    }else{

        let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
        let resultInfo  = new Buffer(JsonString).toString('base64');
        result = resultInfo
    }
    console.log("URL is",req.url)
    return result
}



//router.get('/v01/account/', checkLogin() ,(req, res, next)=>Main.getAnswer(req, res,next));
//router.get('/v01/account/getCode', checkLogin() ,(req, res, next) =>Main.getCode(req, res,next));
//router.get('/v01/account/saveCode', checkLogin(),(req, res, next) =>Main.saveCode(req, res,next));
//router.get('/v01/account/getAnswerTrue',checkLogin() ,(req, res, next) =>Main.getAnswerTrue(req, res,next));
//router.get('/v01/account/saveAnswer',(req, res, next) =>Main.saveAnswer(req, res,next));
//router.post('/v01/account/getAnswerArray',checkLogin() ,(req, res, next) =>Main.getAnswerList(req, res,next));
//router.post('/v01/account/SignCheck',(req, res, next) =>Main.SignCheck(req, res,next));
//router.post('/v01/account/doLogin',(req, res, next) =>Main.doLogin(req, res,next));
//router.get('/v01/account/getTime',(req, res, next) =>Main.getTime2(req, res,next));
//router.get('/v01/account/getGlobal',(req, res, next) =>Main.getGlobal(req, res,next));
//router.post('/v01/account/saveAnswerList',checkLogin() ,(req, res, next) =>Main.saveAnswerList(req, res,next));
//router.post('/v01/account/deleteUser',(req, res, next) =>Main.deleteUser(req, res,next));


router.get('/v01/account/getItemList',(req, res, next) =>Register.getItemList(req, res,function(result) {
  console.log("result is",result)
  res.end(JSON.stringify(result))
}))



router.post('/v01/account/doLoginAccount',(req, res, next) =>Register.doLoginAccount(req, res,function(result) {
  console.log("result is",result)
  let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
  let resultInfo  = new Buffer(JsonString).toString('base64');
  res.end(resultInfo)

}) );
router.post('/v01/account/doLoginID',(req, res, next) =>Register.doLoginID(req, res,function(result) {
  console.log("result is",result)
  let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
  let resultInfo  = new Buffer(JsonString).toString('base64');
  res.end(resultInfo)

}) );

router.post('/v01/account/changePassWd',(req, res, next) =>Register.changePassWd(req, res,function(result) {
  console.log("result is",result)
  let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
  let resultInfo  = new Buffer(JsonString).toString('base64');
  res.end(resultInfo)

}) );

router.post('/v01/account/getOrder',(req, res, next) =>Register.getOrder(req, res,function(result) {
  console.log("result is",result)
  let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
  let resultInfo  = new Buffer(JsonString).toString('base64');
  res.end(resultInfo)

}) )

router.post('/v01/account/sureOrder',(req, res, next) =>Register.sureOrder(req, res,function(result) {
  console.log("result is",result)
  res.end(JSON.stringify(result))

}) )


router.post('/v01/account/share',(req, res, next) =>Register.share(req, res,function(result) {
  console.log("result is",result)
  let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
  let resultInfo  = new Buffer(JsonString).toString('base64');
  res.end(resultInfo)

}) )

router.get('/v01/account/getAnswerUrl',(req, res, next) =>Register.getAnswerUrl(req, res,function(result) {
  console.log("result is",result)
  res.end(JSON.stringify(result))
}))

router.get('/v01/account/getAnswerRoom',(req, res, next) =>Register.getAnswerRoom(req, res,function(result) {
  console.log("result is",result)
  res.end(JSON.stringify(result))
}))



router.get('/v01/account/getCutNum',(req, res, next) =>Register.getCutNum(req, res,function(result) {
    console.log("result is",result)
    res.end(JSON.stringify(result))
}))



router.post('/v01/account/getCutAnswer',checkCutSign(),(req, res, next) =>Main.getAnswerList(req, res,function(result) {
    console.log("result is",result)
    res.end(JSON.stringify(result))
}))


//签到
router.post('/v01/account/signUp',(req, res, next) =>Register.signUp(req, res,function(result) {
    console.log("result is",result)
    let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify(result));
    let resultInfo  = new Buffer(JsonString).toString('base64');
    res.end(resultInfo)
}))



//========================================================================================================================

router.all('/v01/account/transfer',(req, res, next)  =>getBody(req, res,function(body) {
    Register.transfer(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}))


//轮训获取二维码信息
router.all('/v01/account/getQrCode',(req, res, next) =>getBody(req, res,function(body) {
    Taobao.getQrCodeUrl(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//轮训获取二维码信息
router.all('/v01/taobao/saveUrl',(req, res, next) =>getBody(req, res,function(body) {
    Taobao.saveUrl(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));


//获取推广链接
router.all('/v01/account/getGeneralizeUrl',(req, res, next) =>getBody(req, res,function(body) {
    Taobao.getGeneralizeUrl(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//保存订单
router.all('/v01/account/saveOrder',(req, res, next) =>getBody(req, res,function(body) {
    Taobao.saveOrder(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}))

//修改返利比率
router.all('/v01/account/chagneGlobal',(req, res, next) =>getBody(req, res,function(body) {
    Taobao.chagneGlobal(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//修改返利比率
router.all('/v01/account/saveSearch',(req, res, next) =>getBody(req, res,function(body) {
    Taobao.saveSearch(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//保存头像
router.all('/v01/account/saveUserInfo',(req, res, next) =>getBody(req, res,function(body) {
    // console.log("bod ",body)
    Taobao.saveUserInfo(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//修改密码
router.all('/v01/account/changePassWdLogin',(req, res, next) =>getBody(req, res,function(body) {
    // console.log("bod ",body)
    Taobao.changePassWd(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//获取订单信息
router.all('/v01/account/getOrderInfo',(req, res, next) =>getBody(req, res,function(body) {
    // console.log("bod ",body)
    Taobao.getOrderInfo(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//获取订单信息
router.all('/v01/account/changeGlobalUrl',(req, res, next) =>getBody(req, res,function(body) {
    // console.log("bod ",body)
    Taobao.changeGlobalUrl(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//获取转账
router.all('/v01/account/getTransLog',(req, res, next) =>getBody(req, res,function(body) {
    // console.log("bod ",body)
    Taobao.getTransLog(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));

//查询
router.all('/v01/account/findByMsg',(req, res, next) =>getBody(req, res,function(body) {
    // console.log("bod ",body)
    Taobao.findByMsg(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));


router.all('/v01/account/getCode',(req, res, next) =>getBody(req, res,function(body) {
    console.log("1111111111111result is",body)
    Register.getCode(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })

}) );

router.all('/v01/account/register',(req, res, next) => getBody(req, res,function(body) {
    console.log("result is",body)
    Register.register(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}) );

// 热销高佣产品
router.all('/v01/account/hotProducts',(req, res, next) => getBody(req, res,function(body) {
    console.log("result is",body)
    Taobao.hotProducts(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}) );

// 热销高佣产品
router.all('/v01/account/clientTable',(req, res, next) => getBody(req, res,function(body) {
    console.log("result is",body)
    Taobao.clientTable(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}) );



// 分享信息
router.all('/v01/account/sonInfo',(req, res, next) => getBody(req, res,function(body) {
    console.log("result is",body)
    Taobao.sonInfo(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}) );


// 分享详细信息
router.all('/v01/account/sonDetail',(req, res, next) => getBody(req, res,function(body) {
    console.log("result is",body)
    Taobao.sonDetail(req, res,body,function(result) {
        let resultString =  retClient(req,result)
        res.end(resultString)
    })
}));



module.exports = router;
